<?php
namespace app\provider;
use zhanshop\App;
use zhanshop\client\Httpclient;
use zhanshop\Log;

class SnsTokenProvider
{
    protected $vivoKey = 'vivo:token:';
    protected $huaweiKey = 'huawei:token:';

    /**
     * 获取华为的token相关信息
     * @param string $app
     * @return void
     */
    public function getHuawei(string $app)
    {
        $cacheKey = $this->huaweiKey.$app;
        $data = App::cache()->get($cacheKey);
        if($data && is_string($data)){
            $data = json_decode($data, true);
            if($data){
                return $data;
            }
        }
        return App::database()->model("sns_huawei")->where(['app' => $app])->find();
    }

    /**
     * 设置华为token
     * @return void
     * @throws \RedisException
     */
    public function setHuawei()
    {
        $huaweis = App::database()->model("sns_huawei")->order('id desc')->limit(200)->select();
        foreach ($huaweis as $huawei){
            $cacheKey = $this->huaweiKey.$huawei['app'];
            $ttl = App::cache()->ttl($cacheKey);
            if($ttl <= 1800){
                $resp = (new Httpclient())->setHeader("Content-Type", "application/json")->request('https://connect-api.cloud.huawei.com/api/oauth2/v1/token', "POST", json_encode([
                    'grant_type' => 'client_credentials',
                    'client_id' => $huawei['client_id'],
                    'client_secret' => $huawei['client_secret']
                ]));
                if($resp['code'] != 200){
                    App::log()->push($huawei['client_id'].'##huawei##token获取失败##'.$resp['body'], Log::ERROR, "ERROR");
                }else{
                    $body = json_decode($resp['body'], true);
                    if(isset($body['access_token']) && isset($body['expires_in'])){
                        App::database()->model("sns_huawei")->where(['id' => $huawei['id']])->update(['access_token' => $body['access_token']]);
                        App::cache()->set($cacheKey, json_encode(App::database()->model("sns_huawei")->where(['id' => $huawei['id']])->find()), intval($body['expires_in']) - 3600);
                    }else{
                        App::log()->push($huawei['client_id'].'##huawei##token参数获取失败##'.$resp['body'], Log::ERROR, "ERROR");
                    }
                }
            }
        }
    }

    /**
     * 获取vivo的token相关信息
     * @param string $app
     * @return mixed|string|null
     * @throws \RedisException
     */
    public function getVivo(string $app)
    {
        $cacheKey = $this->vivoKey.$app;
        $data = App::cache()->get($cacheKey);
        if($data && is_string($data)){
            $data = json_decode($data, true);
            if($data){
                return $data;
            }
        }
        return App::database()->model("sns_vivo")->where(['app' => $app])->find();
    }
    public function setVivo()
    {
        $list = App::database()->model("sns_vivo")->order('id desc')->limit(200)->select();
        if($list){
            foreach($list as $vivo){
                $cacheKey = $this->vivoKey.$vivo['app'];
                $ttl = App::cache()->ttl($cacheKey);
                if($ttl <= 86400 * 7){
                    if($vivo['refresh_token']){
                        $url = 'https://marketing-api.vivo.com.cn/openapi/v1/oauth2/refreshToken?client_id='.$vivo['client_id'].'&client_secret='.$vivo['client_secret'].'&refresh_token='.$vivo['refresh_token'];
                        $curl = new Httpclient();
                        $resp = $curl->debug()->request($url);
                        $body = json_decode($resp['body'] ?? '', true);
                        if(isset($body['data']) && isset($body['data']['access_token'])){
                            App::cache()->set($cacheKey, json_encode($body['data']), 3600*24*320);
                            App::database()->model("sns_vivo")->where(['id' => $vivo['id']])->update(['access_token' => $body['data']['access_token'], 'refresh_token' => $body['data']['refresh_token']]);

                            App::cache()->set($cacheKey, json_encode(App::database()->model("sns_vivo")->where(['id' => $vivo['id']])->find()), 3600*24*320);

                        }else{
                            App::log()->push($vivo['client_id'].'##vivo##token刷新参数失败##'.$resp['body'], Log::ERROR, "ERROR");
                        }
                    }else{
                        $curl = new Httpclient();
                        $resp = $curl->debug()->request("https://marketing-api.vivo.com.cn/openapi/v1/oauth2/token?client_id=".$vivo['client_id']."&client_secret=".$vivo['client_secret'].'&grant_type=code&code='.$vivo['grant_code']);
                        if($resp['code'] != 200){
                            App::log()->push($vivo['client_id'].'##vivo##token获取失败##'.$resp['body'], Log::ERROR, "ERROR");
                        }else{
                            $body = json_decode($resp['body'], true);
                            if(isset($body['data']) && isset($body['data']['access_token'])){
                                App::database()->model("sns_vivo")->where(['id' => $vivo['id']])->update(['access_token' => $body['data']['access_token'], 'refresh_token' => $body['data']['refresh_token']]);
                                App::cache()->set($cacheKey, json_encode(App::database()->model("sns_vivo")->where(['id' => $vivo['id']])->find()), 3600*24*320);
                            }
                        }
                    }
                }
            }
        }
    }
}